var app = angular.module('indexApp', []);

app.controller('pageCtrl', ['$scope', '$http', function($scope, $http) {
    var vm = this;
    vm.headers = [];
    vm.params = [];
    vm.method = 'GET';
    vm.protocol = 'http://';
    vm.data = '';
    vm.resHistory = [];

    //vm.url = "192.168.0.10/interface4.0/api/evalution";
    //vm.headers.push({ key: 'Authorization', value: 'Basic BA455A1E64CE58B26927414D69E91CD8' });
    vm.data = '{"star":3}';

    console.log();

    vm.setUrl = function() {
        if (vm.url && vm.url.indexOf('http://') >= 0) {
            vm.protocol = 'http://';
            vm.url = vm.url.substring(vm.url.indexOf('http://') + 7);
        } else if (vm.url && vm.url.indexOf('https://') >= 0) {
            vm.protocol = 'https://';
            vm.url = vm.url.substring(vm.url.indexOf('http://') + 8);
        }
    };
    
    vm.request = function() {
        //var requestData = {};
        var requestHeader = {};

        angular.forEach(vm.headers, function(item, i) {
            requestHeader[item.key] = item.value;
        });
        var paramString = '';
        angular.forEach(vm.params, function(item, i) {
            paramString = paramString + ((paramString.length == 0) ? '?' : '&') + item.key + '=' + item.value;
        });
        var url = vm.protocol + vm.url + paramString;
        var date = moment().format('YYYY-MM-DD hh:mm:ss.SSS');
        //data = JSON.parse(vm.data);
        $http.post('/api/request', {
                url: url,
                method: vm.method,
                requestData: JSON.parse(vm.data),
                requestHeader: requestHeader
            })
            .success(function(res, status, headers, config) {
                if (res.error) {
                    alert('出错了，错误信息：' + res.error);
                } else {
                    vm.resHistory.splice(0, 0, {
                        date:date,
                        url: '['+vm.method+'] '+url,
                        response:res.data
                    });
                }
            })
            .error(function(data, status, headers, config) {
                alert('服务器错误！');
            });
    };
}]);
